﻿using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Oprator;

namespace ELearning.API.HandleAttribute
{
    /// <summary>
    /// 认证类继承
    /// </summary>
    public class RequestAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 登录token记录操作service
        /// </summary>
        private TLoginTokenService tlLoginTokenService => new TLoginTokenService();

        public override void OnAuthorization(HttpActionContext actionContext)
        {            
            if (!Guid.TryParse(actionContext.Request.Headers.Authorization?.ToString(), out Guid g))
            {
                base.OnAuthorization(actionContext);
            }
            else {
                // 是否不需要验证 或者 已经登录
                if (SkipAuthorization(actionContext) || IsLogin(actionContext))
                return;
            actionContext.Response = GetResponse();
            }
        }

        /// <summary>
        /// 返回信息接口
        /// </summary>
        private HttpResponseMessage GetResponse()
        {
            var response = new { code = 401, message = CommonConst.Msg_NoLogin, data = false };
            return JsonHelper.ToHttpResponseMessage(response);
        }

        /// <summary>
        /// 判断是否匿名使用接口
        /// </summary>
        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            if (!actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>())
                return actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>();
            return true;
        }

        /// <summary>
        /// 是否已经登录
        /// </summary>
        private bool IsLogin(HttpActionContext actionContext)
        {
            var authorization = Guid.Empty.ToString(); // MD5值
            if (actionContext.Request.Headers.Authorization != null)
            {
                authorization = actionContext.Request.Headers.Authorization.ToString();
            }

            var user = OperatorProvider.Provider.GetCurrent(authorization);
            //if (user == null)
            //{
            //    var m = tlLoginTokenService.Find(i => i.Token == authorization && i.PassDateTime > DateTime.Now);
            //    return m != null;
            //}
            return user.IsNotNull();
        }
    }
}